package io.renren.modules.task.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.HttpClientUtil;
import io.renren.common.utils.R;
import io.renren.common.utils.SpringContextUtils;
import io.renren.datasource.annotation.DataSource;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.task.dao.TestDaos;
import io.renren.modules.task.entity.*;
import io.renren.modules.task.model.AgvParam;
import io.renren.modules.task.model.Position;
import io.renren.modules.task.service.MtCcWarehousePointService;
import io.renren.modules.task.service.SqlServerService;
import io.renren.modules.task.service.TestService;
import io.renren.modules.task.wcs.DDJRunnableCallable;
import io.renren.modules.task.wcs.QGSThreadPool;
import io.renren.modules.task.websocket.MessageModule;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ioserver.IOServerService;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author: weihongyang
 * @Date: 2019/4/24 10:34
 * @Version 1.0
 */
@RestController
@Api(description = "测试接口")
@RequestMapping("/test")
@DependsOn("springContextUtils")
// 注意 Controller层必须加@DependsOn() 否则项目打包成jar包会报错空指针异常
public class TestController extends AbstractController {
    @Autowired
    private MtCcWarehousePointService mtCcWarehousePointService;

    @Autowired
    private TestService testService;

    @Autowired
    private TestDaos testDaos;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TestBean testBean;

    @Autowired
    private MessageModule messageModule;

    private SalveThread t = new SalveThread();
    IOServerService ioServerService = new IOServerService();


    //QGSThreadPool threadPool = new QGSThreadPool();

    @ApiOperation(value = "测试事务", notes = "测试事务")
    @Transactional
    @PostMapping("/cesshiwu/{s}")
    @DataSource("slave1")
    public R test(@PathVariable("s") String s){
        String[] sa = s.split(",");
        List<String> sas = new ArrayList<>();
        Arrays.stream(sa).forEach(sb->sas.add(sb));
        Integer integer = testService.deleteByNames(sas);
        return R.ok().put("result",integer);
    }
    /**
     * 往sql-server 里面插入数据
     **/
    @ApiOperation(value = "insert-slave源", notes = "insert-slave源")
    @PostMapping("/insertSlave")
    @DataSource("slave1")
    public R insertSlave(@RequestBody ThreadFlag threadFlag){
        int min = 1;
        int max = 1000;
        int intBounded = min + ((int) (new Random().nextFloat() * (max - min)));
        Integer a = threadFlag.getFlagAS();
        String aa = a.toString();
        TestEntity2 testEntity = new TestEntity2();
        testEntity.setUserNames(aa);
        testEntity.setPassword("aaa");
        testEntity.setId(intBounded);
        //todo
        if(testBean.insertOne(testEntity) ==1){
            return R.ok("插入成功");
        }else {
            return R.error("插入失败");
        }
    }

    /**
     *  监听sql-server 并且把数据 一直到mysql
     **/
    @ApiOperation(value = "测试多数据源-count", notes = "测试多数据源-count")
    @PostMapping("/multiDatasourceCount")
    @DataSource("slave1")
    public R multiDatasourceCount(@RequestBody ThreadFlag flag){
        //注意***
        //@DependsOn("springContextUtils")
        //Controller层必须加@DependsOn() 否则项目打包成jar包会报错空指针异常

        // 一个接口 就是一个nio 线程。不同时间段 调用相同接口，都是不同的线程在跑。
        Integer flages = flag.getFlagAS();
        System.err.println("当前nio线程："+Thread.currentThread().getName());

        if(flages == 1){
            if(!t.isAlive()){
                t.start();
            }
            return R.ok("线程已近 启动");
        }
        if(flages ==3){
            t.wakeup();
            return R.ok("线程已被唤醒");
        }else{
            //t.interrupt();
            t.shutdown();
            return R.error("线程已近关闭");
        }
    }


    //websocket 对 一个点
    @ApiOperation(value = "testWebsocketToOne", notes = "testWebsocketToOne")
    @GetMapping("/websockettest/{userId}/{msg}")
    public R testWebsocketToOne(@PathVariable("userId") String userId,@PathVariable("msg") String msg) {
        if(messageModule.sendMessageToSomeone(msg,userId)){
            return R.ok().put("status","success");
        }else {
            return R.error("发送失败");
        }
    }

    //websocket 对 所有人
    @ApiOperation(value = "testWebsocketToAll", notes = "testWebsocketToAll")
    @GetMapping("/websockettest/{msg}")
    public R testWebsocketToAll(@PathVariable("msg") String msg) throws IOException {
        if(messageModule.sendMessageToAll(msg)){
            return R.ok().put("status","success");
        }else {
            return R.error("发送失败");
        }
    }



    @SysLog("测试修改工作台号")
    @ApiOperation(value = "修改工作台号", notes = "修改工作台号")
    @PostMapping("modify")
    public String updateConsole(){
        SysUserEntity sysUserEntity = sysUserService.getById(7);
        //sysUserService.updateConsoleCodeByUserId();
        return "修改成功";
    }

    //发起堆垛机任务，并且堆垛机给出反馈
    @ApiOperation(value = "sendDDJTaskTest", notes = "sendDDJTaskTest")
    @GetMapping("/sendDDJTaskTest")
    public R sendDDJTaskTest() {
        Short destLayer = 1;
        Short destCol = 1;
        Short takePosition = 6;

        DDJRunnableCallable<Integer> task = new DDJRunnableCallable<>(destLayer,destCol,takePosition,ioServerService);

        logger.info("线程池是否关闭："+ QGSThreadPool.executor.isShutdown());
        //Future<?> future = threadPool.getExecutor().submit(task);
        Future<?> future = QGSThreadPool.executor.submit(task);
        logger.info("是否正在执行："+future.isDone());
        Object r = new Object();
        try {
            r = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        /*threadPool.getExecutor().shutdown();
         */
        return R.ok().put("result",r);
    }

    @PostMapping("/to/agv")
    @ApiOperation(value = "空车回库操作", notes = "空车回库操作")
    public R selectEmptyPointToAgv() throws Exception {
        String url = "http://192.168.0.124/rcs/services/rest/hikRpcService/genAgvSchedulingTask";
        String taskTyp = "F01";
        Position position = new Position();
        position.setPositionCode("A");
        position.setType("00");
        Position position1 = new Position();
        position1.setType("00");
        position1.setPositionCode("B");
        Object[] positionCodePath = {position,position1};
        AgvParam agvParam = new AgvParam();
        agvParam.setReqCode("11111");
        agvParam.setTaskTyp(taskTyp);
        agvParam.setPositionCodePath(positionCodePath);
        String resultMsg = null;//获取服务端返回的参数
        String param = JSONObject.toJSONString(agvParam);
        resultMsg = HttpClientUtil.post(url, param);// 以post形式调用webservice
        return R.ok(resultMsg);
    }

}
